<template>
    <!-- 操作按钮区域 -->
    <el-button plain type="primary" style="margin-bottom: 10px;" @click="Open()">添加</el-button>
    <!-- 批量删除按钮：当没有选中项时禁用，防止用户误操作 -->
    <el-button 
        plain 
        type="danger" 
        style="margin-bottom: 10px; margin-left: 10px;" 
        @click="batchDelete" 
        :disabled="multipleSelection.length === 0">
        批量删除
    </el-button>
    <el-button plain type="primary" style="float: right;" @click="handleExport">导出</el-button>
    
    <!-- 数据表格：支持多选和批量操作 -->
    <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        @selection-change="handleSelectionChange"
        row-key="id"
        @expand-change="handleExpandChange">
        <!-- 展开列：用于展示下级数据 -->
        <el-table-column type="expand" width="50">
            <template #default="props">
                <div v-if="!props.row.isLeaf && props.row.children && props.row.children.length > 0">
                    <el-table :data="props.row.children" style="width: 100%" border>
                        <el-table-column type="index" label="序号" width="60" />
                        <el-table-column prop="bomCode" label="BOM编码" width="120" />
                        <el-table-column prop="bomName" label="BOM名称" width="150" />
                        <el-table-column prop="bomVersion" label="BOM版本" width="100" />
                        <el-table-column prop="useNum" label="使用数量" width="100" />
                        <el-table-column prop="bomDesc" label="BOM描述" width="150" />
                        <el-table-column prop="level" label="层级" width="80" />
                        <el-table-column label="是否叶子节点" width="120">
                            <template #default="scope">
                                <span :class="scope.row.isLeaf ? 'green-text' : 'red-text'">
                                    {{ scope.row.isLeaf ? '是' : '否' }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" width="180">
                            <template #default="scope">
                                <el-button link type="primary" @click="handleAddChild(scope.row)" v-if="!scope.row.isLeaf">添加下级</el-button>
                                <el-button link type="warning" @click="OpenUpdate(scope.row)">编辑</el-button>
                                <el-button link type="danger" @click="Del(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div v-else-if="!props.row.isLeaf" class="no-children">
                    <el-empty description="暂无下级数据">
                        <el-button type="primary" @click="handleAddChild(props.row)">添加下级</el-button>
                    </el-empty>
                </div>
                <div v-else class="no-children">
                    <el-empty description="叶子节点无下级数据" />
                </div>
            </template>
        </el-table-column>
        <!-- 选择列：用于批量操作的复选框 -->
        <el-table-column type="selection" width="55" />
        <el-table-column fixed type="index" label="序号" width="60" />
        <el-table-column prop="bomCode" label="BOM编码" width="120" />
        <el-table-column prop="bomName" label="BOM名称" width="150" />
        <el-table-column prop="bomVersion" label="BOM版本" width="100" />
        <el-table-column prop="useNum" label="使用数量" width="100" />
        <el-table-column prop="bomDesc" label="BOM描述" width="150" />
        <el-table-column prop="level" label="层级" width="80" />
        <el-table-column label="是否叶子节点" width="120">
            <template #default="scope">
                <span :class="scope.row.isLeaf ? 'green-text' : 'red-text'">
                    {{ scope.row.isLeaf ? '是' : '否' }}
                </span>
            </template>
        </el-table-column>
        <el-table-column prop="createrPeople" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
            </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.updateTime).format('YYYY-MM-DD') }}
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="180">
            <template #default="scope">
                <el-button link type="primary" @click="handleAddChild(scope.row)">添加下级</el-button>
                <el-button link type="warning" @click="OpenUpdate(scope.row)">编辑</el-button>
                <el-button link type="danger" @click="Del(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 添加BOM弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加BOM" width="500px">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
            <el-form-item label="BOM编码" prop="bomCode">
                <el-input v-model="ruleForm.bomCode" placeholder="请输入BOM编码" />
            </el-form-item>
            <el-form-item label="BOM名称" prop="bomName">
                <el-input v-model="ruleForm.bomName" placeholder="请输入BOM名称" />
            </el-form-item>
            <el-form-item label="物料群组" prop="materialGroupId">
                <el-select v-model="ruleForm.materialGroupId" placeholder="请选择物料群组" style="width: 100%">
                    <el-option v-for="item in materialGroupOptions" :key="item.id" :label="item.materialGroupName"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="BOM版本" prop="bomVersion">
                <el-input v-model="ruleForm.bomVersion" placeholder="请输入BOM版本" />
            </el-form-item>
            <el-form-item label="工序" prop="processManagementId">
                <el-select v-model="ruleForm.processManagementId" placeholder="请选择工序" style="width: 100%">
                    <el-option v-for="item in processOptions" :key="item.id" :label="item.processName"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="使用数量" prop="useNum">
                <el-input-number v-model="ruleForm.useNum" :min="0" :step="1" style="width: 100%" />
            </el-form-item>
            <el-form-item label="BOM描述" prop="bomDesc">
                <el-input v-model="ruleForm.bomDesc" type="textarea" placeholder="请输入BOM描述" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 修改BOM弹窗 -->
    <el-dialog v-model="dialogVisibleUpdate" title="修改BOM" width="500px">
        <el-form ref="ruleFormRef" :model="ruleFormUpdate" :rules="rules" label-width="120px">
            <el-form-item label="BOM编码" prop="bomCode">
                <el-input v-model="ruleFormUpdate.bomCode" placeholder="请输入BOM编码" />
            </el-form-item>
            <el-form-item label="BOM名称" prop="bomName">
                <el-input v-model="ruleFormUpdate.bomName" placeholder="请输入BOM名称" />
            </el-form-item>
            <el-form-item label="物料群组" prop="materialGroupId">
                <el-select v-model="ruleFormUpdate.materialGroupId" placeholder="请选择物料群组" style="width: 100%">
                    <el-option v-for="item in materialGroupOptions" :key="item.id" :label="item.materialGroupName"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="BOM版本" prop="bomVersion">
                <el-input v-model="ruleFormUpdate.bomVersion" placeholder="请输入BOM版本" />
            </el-form-item>
            <el-form-item label="工序" prop="processManagementId">
                <el-select v-model="ruleFormUpdate.processManagementId" placeholder="请选择工序" style="width: 100%">
                    <el-option v-for="item in processOptions" :key="item.id" :label="item.processName"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="使用数量" prop="useNum">
                <el-input-number v-model="ruleFormUpdate.useNum" :min="0" :step="1" style="width: 100%" />
            </el-form-item>
            <el-form-item label="BOM描述" prop="bomDesc">
                <el-input v-model="ruleFormUpdate.bomDesc" type="textarea" placeholder="请输入BOM描述" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 选择下级BOM对话框 -->
    <el-dialog v-model="childDialogVisible" title="选择下级" width="80%" :close-on-click-modal="false">
        <div class="selection-container">
            <div class="selection-header">
                <span>选择下级</span>
            </div>
            <div class="selection-panels">
                <!-- 左侧可选物料列表 -->
                <div class="left-panel">
                    <div class="panel-header">
                        <span>{{ availableBoms.length || 0 }} 项</span>
                        <div class="refresh-icon" @click="refreshAvailableBoms">
                            <el-icon><Refresh /></el-icon>
                        </div>
                    </div>
                    <div class="search-box">
                        <el-input v-model="childSearchKey" placeholder="请输入搜索内容" clearable @input="filterAvailableBoms">
                            <template #prefix>
                                <el-icon><Search /></el-icon>
                            </template>
                        </el-input>
                    </div>
                    <div class="material-table">
                        <el-table :data="availableBoms" style="width: 100%" height="400" border 
                            @row-click="handleSelectBom" 
                            :row-class-name="getRowClassName"
                            highlight-current-row>
                            <el-table-column prop="bomName" label="Bom名称" width="150"></el-table-column>
                            <el-table-column prop="bomCode" label="Bom编码" width="120"></el-table-column>
                            <el-table-column prop="bomVersion" label="BOM版本" width="100"></el-table-column>
                            <el-table-column prop="bomDesc" label="BOM描述" width="150"></el-table-column>
                        </el-table>
                        <div class="pagination-mini">
                            <el-pagination layout="prev, pager, next" :total="childPagination.totalcount"
                                :page-size="childPagination.PageSize" :current-page="childPagination.PageIndex"
                                @current-change="handleChildPageChange"></el-pagination>
                        </div>
                    </div>
                </div>

                <!-- 中间按钮区域 -->
                <div class="transfer-buttons">
                    <div class="arrow-right" @click="addToSelected">
                        <el-icon><ArrowRight /></el-icon>
                    </div>
                    <div class="arrow-left" @click="removeFromSelected">
                        <el-icon><ArrowLeft /></el-icon>
                    </div>
                </div>

                <!-- 右侧已选物料列表 -->
                <div class="right-panel">
                    <div class="panel-header">
                        <span>{{ selectedBoms.length || 0 }} 项</span>
                    </div>
                    <div class="search-box">
                        <el-input placeholder="请输入搜索内容" clearable>
                            <template #prefix>
                                <el-icon><Search /></el-icon>
                            </template>
                        </el-input>
                    </div>
                    <div class="material-table">
                        <div class="empty-data" v-if="selectedBoms.length === 0">
                            <div class="empty-icon">
                                <el-icon><Document /></el-icon>
                            </div>
                            <div class="empty-text">暂无数据</div>
                        </div>
                        <el-table v-else :data="selectedBoms" style="width: 100%" height="400" border 
                            @row-click="handleSelectFromSelected"
                            :row-class-name="getSelectedRowClassName"
                            highlight-current-row>
                            <el-table-column prop="bomCode" label="编码" width="100"></el-table-column>
                            <el-table-column prop="bomName" label="名称" width="120"></el-table-column>
                            <el-table-column prop="workOrder" label="工序" width="100"></el-table-column>
                            <el-table-column prop="usage" label="用量" width="80"></el-table-column>
                            <el-table-column prop="remark" label="备注" width="120"></el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="childDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitChildBoms">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <!--分页-->
    <div class="pagination-container">
        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[3, 6, 9, 12]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalcount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" class="custom-pagination" />
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useCounterStore } from '@/stores/counter';
import { Search, Refresh, ArrowRight, ArrowLeft, Document } from '@element-plus/icons-vue';

// 获取用户信息
const pinia = useCounterStore();

// BOM表格数据
const tableData = ref<any[]>([]);
// 存储用户选中的表格行数据，用于批量操作
const multipleSelection = ref<any[]>([]);
// 物料群组选项数据，用于下拉选择
const materialGroupOptions = ref<any[]>([]);
// 工序选项数据，用于下拉选择
const processOptions = ref<any[]>([]);

// BOM分页参数
const page = reactive({
    PageIndex: 1,
    PageSize: 5,
    totalcount: 0
});

// 物料群组分页参数
const pageMaterialGroup = reactive({
    PageIndex: 1,
    PageSize: 100,
    totalcount: 0
});

// 工序分页参数
const pageProcess = reactive({
    PageIndex: 1,
    PageSize: 100,
    totalcount: 0
});

// 页面初始化钩子
onMounted(() => {
    GetMaterialGroup(); // 获取物料群组选项
    GetProcess(); // 获取工序选项
    GetBom(); // 获取BOM列表数据
});

// 获取物料群组选项数据
const GetMaterialGroup = () => {
    axios.get('/api/MaterialManagement/GetMaterialGroup', { params: pageMaterialGroup }).then(res => {
        console.log('物料群组API响应:', res.data); // 添加调试日志
        if (res.data.code == 200) {
            materialGroupOptions.value = res.data.totalPage || [];
            pageMaterialGroup.totalcount = res.data.totalcount || 0;
            console.log('获取到物料群组数据:', materialGroupOptions.value);
        } else {
            console.error('获取物料群组失败:', res.data.message);
            ElMessage.error(res.data.message || '获取物料群组失败');
        }
    }).catch(error => {
        console.error('获取物料群组失败:', error);
        ElMessage.error('获取物料群组失败');
    });
};

// 获取工序选项数据
const GetProcess = () => {
    axios.get('/api/ProcessManagement/GetProcessManagements', { params: pageProcess }).then(res => {
        console.log('工序API响应:', res.data); // 添加调试日志
        if (res.data.code == 200) {
            processOptions.value = res.data.totalPage || [];
            pageProcess.totalcount = res.data.totalcount || 0;
            console.log('获取到工序数据:', processOptions.value);
        } else {
            console.error('获取工序失败:', res.data.message);
            ElMessage.error(res.data.message || '获取工序失败');
        }
    }).catch(error => {
        console.error('获取工序失败:', error);
        ElMessage.error('获取工序失败');
    });
};

// 获取BOM列表数据
const GetBom = () => {
    axios.get('/api/MaterialManagement/GetBom', { params: page }).then(res => {
        if (res.data.code == 200) {
            tableData.value = res.data.totalPage;
            page.totalcount = res.data.totalcount;
        }
    }).catch(error => {
        console.error('获取BOM列表失败:', error);
        ElMessage.error('获取BOM列表失败');
    });
};

// 处理行展开/收起事件
const handleExpandChange = (row: any, expanded: boolean) => {
    // 只有非叶子节点才可能有子级数据
    if (expanded && !row.isLeaf) {
        console.log('展开非叶子节点:', row.bomCode, row.bomName);
    }
};

// 控制添加弹窗显示
const dialogVisible = ref(false);
const Open = () => {
    dialogVisible.value = true;
};

// 表单引用
const ruleFormRef = ref<FormInstance>();

// 添加BOM表单数据
const ruleForm = reactive({
    "bomCode": "",
    "bomName": "",
    "materialGroupId": null,
    "bomVersion": "",
    "processManagementId": null,
    "useNum": 0,
    "bomDesc": "",
    "parentId": null,
    "createrPeople": pinia.piniaDto.accountName
});

// 表单验证规则
const rules = reactive<FormRules>({
    bomCode: [
        { required: true, message: '请输入BOM编码', trigger: 'blur' },
    ],
    bomName: [
        {
            required: true,
            message: '请输入BOM名称',
            trigger: 'blur',
        },
    ],
    materialGroupId: [
        {
            required: true,
            message: '请选择物料群组',
            trigger: 'change',
        }
    ],
    bomVersion: [
        {
            required: true,
            message: '请输入BOM版本',
            trigger: 'blur',
        },
    ],
    processManagementId: [
        {
            required: true,
            message: '请选择工序',
            trigger: 'change',
        }
    ],
    useNum: [
        {
            required: true,
            message: '请输入使用数量',
            trigger: 'blur',
        },
    ],
    bomDesc: [
        {
            required: true,
            message: '请输入BOM描述',
            trigger: 'blur',
        },
    ],
});

// 提交添加BOM表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post('/api/MaterialManagement/AddBom', ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    dialogVisible.value = false;
                    GetBom(); // 提交成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message);
                }
            }).catch(error => {
                console.error('添加BOM失败:', error);
                ElMessage.error('添加BOM失败');
            });
        } else {
            console.log('表单验证失败:', fields);
        }
    });
};

// 分页大小改变处理
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    page.PageSize = val;
    GetBom();
};

// 分页页码改变处理
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    page.PageIndex = val;
    GetBom();
};

// 控制修改弹窗显示
const dialogVisibleUpdate = ref(false);

// 控制选择下级弹窗显示
const childDialogVisible = ref(false);
// 当前选中的父级BOM
const currentParentBom = ref<any>(null);
// 可选BOM列表
const availableBoms = ref<any[]>([]);
// 已选BOM列表
const selectedBoms = ref<any[]>([]);
// 子级BOM搜索关键字
const childSearchKey = ref('');
// 当前选中的可用BOM
const selectedAvailableBom = ref<any>(null);
// 当前选中的已选BOM
const selectedSelectedBom = ref<any>(null);

// 子级BOM分页参数
const childPagination = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalcount: 0
});

// 打开修改弹窗并填充数据
const OpenUpdate = (row: any) => {
    dialogVisibleUpdate.value = true;
    ruleFormUpdate.id = row.id;
    ruleFormUpdate.bomCode = row.bomCode;
    ruleFormUpdate.bomName = row.bomName;
    ruleFormUpdate.materialGroupId = row.materialGroupId;
    ruleFormUpdate.bomVersion = row.bomVersion;
    ruleFormUpdate.processManagementId = row.processManagementId;
    ruleFormUpdate.useNum = row.useNum;
    ruleFormUpdate.bomDesc = row.bomDesc;
};

// 修改BOM表单数据
const ruleFormUpdate = reactive({
    "id": null,
    "bomCode": "",
    "bomName": "",
    "materialGroupId": null,
    "bomVersion": "",
    "processManagementId": null,
    "useNum": 0,
    "bomDesc": "",
    "updaterPeople": pinia.piniaDto.accountName
});

// 提交修改BOM表单
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.put('/api/MaterialManagement/UpdateBom', ruleFormUpdate).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    dialogVisibleUpdate.value = false;
                    GetBom(); // 提交成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message);
                }
            }).catch(error => {
                console.error('修改BOM失败:', error);
                ElMessage.error('修改BOM失败');
            });
        } else {
            console.log('表单验证失败:', fields);
        }
    });
};

// 删除BOM
const Del = (id: any) => {
    ElMessageBox.confirm(
        '确定要删除该BOM吗？删除后数据将无法恢复。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 根据API文档，删除接口使用POST方法，参数通过查询参数传递
            axios.post(`/api/MaterialManagement/DeleteBom?Id=${id}&CascadeDelete=false`).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    GetBom(); // 删除成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message);
                }
            }).catch(error => {
                ElMessage.error('删除失败，请重试');
                console.error('Delete error:', error);
            });
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
};

// 导出BOM数据
const handleExport = () => {
    ElMessage.info('导出功能待实现');
    // 实际应用中调用导出API
};

// 打开添加下级对话框
const handleAddChild = (row: any) => {
    console.log('打开添加下级对话框，父级BOM:', row);
    currentParentBom.value = row;
    childDialogVisible.value = true;
    selectedBoms.value = [];
    childSearchKey.value = '';
    childPagination.PageIndex = 1;
    getAvailableBoms();
};

// 获取可用于添加为子级的BOM列表
const getAvailableBoms = async () => {
    try {
        console.log('正在获取可用BOM列表，参数:', {
            pageIndex: childPagination.PageIndex,
            pageSize: childPagination.PageSize,
            bomCode: childSearchKey.value
        });
        
        const response = await axios.get('/api/MaterialManagement/GetBom', {
            params: {
                pageIndex: childPagination.PageIndex,
                pageSize: childPagination.PageSize,
                bomCode: childSearchKey.value
            }
        });

        console.log('可用BOM列表API响应:', response);

        if (response.data && response.data.code === 200) {
            let filteredBoms = response.data.totalPage || [];
            console.log('原始BOM数据:', filteredBoms);
            
            // 过滤掉当前父级BOM及其已有子级
            if (currentParentBom.value) {
                filteredBoms = filteredBoms.filter((bom: any) =>
                    bom.id !== currentParentBom.value.id &&
                    bom.parentId !== currentParentBom.value.id
                );
                console.log('过滤父级BOM后:', filteredBoms);
            }
            
            // 先不过滤空值，看看数据结构
            availableBoms.value = filteredBoms;
            childPagination.totalcount = response.data.totalcount || 0;
            console.log('最终可用BOM列表数据:', availableBoms.value);
        } else {
            const errorMsg = response.data ? response.data.message : '获取可用BOM列表失败';
            console.error('获取可用BOM列表失败:', errorMsg);
            ElMessage.error(errorMsg || '获取可用BOM列表失败');
        }
    } catch (error) {
        console.error('获取可用BOM列表出错:', error);
        ElMessage.error('网络错误，请稍后重试');
    }
};

// 刷新可用BOM列表
const refreshAvailableBoms = () => {
    childSearchKey.value = '';
    childPagination.PageIndex = 1;
    getAvailableBoms();
};

// 过滤可用BOM列表
const filterAvailableBoms = () => {
    childPagination.PageIndex = 1;
    getAvailableBoms();
};

// 子级BOM分页改变
const handleChildPageChange = (page: number) => {
    childPagination.PageIndex = page;
    getAvailableBoms();
};

// 选择可用BOM
const handleSelectBom = (row: any) => {
    selectedAvailableBom.value = row;
    selectedSelectedBom.value = null;
    console.log('选中可用BOM:', row);
};

// 获取可用BOM表格行样式类名
const getRowClassName = ({ row }: { row: any }) => {
    return selectedAvailableBom.value && selectedAvailableBom.value.id === row.id ? 'selected-row' : '';
};

// 选择已选BOM
const handleSelectFromSelected = (row: any) => {
    selectedSelectedBom.value = row;
    selectedAvailableBom.value = null;
    console.log('选中已选BOM:', row);
};

// 获取已选BOM表格行样式类名
const getSelectedRowClassName = ({ row }: { row: any }) => {
    return selectedSelectedBom.value && selectedSelectedBom.value.id === row.id ? 'selected-row' : '';
};

// 添加到已选列表
const addToSelected = () => {
    console.log('尝试添加到已选列表，当前选中的BOM:', selectedAvailableBom.value);
    
    if (!selectedAvailableBom.value) {
        ElMessage.warning('请先选择要添加的BOM');
        return;
    }

    // 检查是否已经在已选列表中
    const exists = selectedBoms.value.some(item => item.id === selectedAvailableBom.value.id);
    if (exists) {
        ElMessage.warning('该BOM已在已选列表中');
        return;
    }

    // 添加默认的工序、用量和备注字段
    const newBom = { 
        ...selectedAvailableBom.value,
        workOrder: '', // 工序名称
        usage: 1, // 用量
        remark: '' // 备注
    };
    
    selectedBoms.value.push(newBom);
    console.log('成功添加到已选列表:', newBom);
    console.log('当前已选列表:', selectedBoms.value);
    
    selectedAvailableBom.value = null;
    ElMessage.success('已添加到选择列表');
};

// 从已选列表中移除
const removeFromSelected = () => {
    if (!selectedSelectedBom.value) {
        ElMessage.warning('请先选择要移除的BOM');
        return;
    }

    const index = selectedBoms.value.findIndex(item => item.id === selectedSelectedBom.value.id);
    if (index !== -1) {
        selectedBoms.value.splice(index, 1);
    }
    selectedSelectedBom.value = null;
};

// 提交添加子级BOM
const submitChildBoms = async () => {
    if (selectedBoms.value.length === 0) {
        ElMessage.warning('请至少选择一个BOM作为子级');
        return;
    }

    try {
        const promises = selectedBoms.value.map(bom => {
            return axios.post('/api/MaterialManagement/AddChildBom', {
                parentBomId: currentParentBom.value.id,
                bomCode: bom.bomCode,
                bomName: bom.bomName,
                materialGroupId: bom.materialGroupId,
                bomVersion: bom.bomVersion,
                processManagementId: bom.processManagementId,
                useNum: bom.usage || 1,
                bomDesc: bom.remark || '',
                createrPeople: pinia.piniaDto.accountName
            });
        });

        const results = await Promise.all(promises);
        const allSuccess = results.every(res => res.data.code === 200);

        if (allSuccess) {
            ElMessage.success('添加下级BOM成功');
            childDialogVisible.value = false;
            GetBom(); // 刷新主列表
        } else {
            ElMessage.warning('部分BOM添加失败，请检查');
        }
    } catch (error) {
        console.error('添加子级BOM出错:', error);
        ElMessage.error('网络错误，请稍后重试');
    }
};

/**
 * 批量选择处理函数
 * 当用户在表格中选择/取消选择行时触发
 * @param val 当前选中的所有行数据数组
 */
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val;
};

/**
 * 批量删除功能
 * 删除用户选中的多条BOM记录
 * 包含数据验证、用户确认、API调用、结果处理等完整流程
 */
const batchDelete = () => {
    // 1. 数据验证：检查是否有选中的数据
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要删除的数据');
        return;
    }
    
    // 2. 提取选中行的ID数组，用于后端删除操作
    const ids = multipleSelection.value.map((item: any) => item.id);
    
    // 3. 显示确认对话框，防止用户误操作
    ElMessageBox.confirm(
        `确定要删除选中的 ${multipleSelection.value.length} 条BOM记录吗？删除后数据将无法恢复。`,
        '批量删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning', // 警告类型的对话框
        }
    )
        .then(async () => {
            // 4. 用户确认删除，批量调用删除接口
            // 根据API文档，删除接口使用POST方法，参数通过查询参数传递
            
   
            
            try {
                // 创建删除任务数组，每个任务包含ID和索引
                const deleteTasks = ids.map((id, index) => ({
                    id,
                    index: index + 1
                }));
                
                // 使用Promise.allSettled确保所有请求都能完成
                const results = await Promise.allSettled(
                    deleteTasks.map(async (task) => {
                        console.log(`正在删除第 ${task.index}/${ids.length} 条记录，ID: ${task.id}`);
                        const response = await axios.post(`/api/MaterialManagement/DeleteBom?Id=${task.id}&CascadeDelete=false`);
                        return { task, response };
                    })
                );
                
                // 统计结果
                let successCount = 0;
                let failCount = 0;
                const failedIds: any[] = [];
                
                results.forEach((result, index) => {
                    if (result.status === 'fulfilled') {
                        const { task, response } = result.value;
                        if (response.data.code === 200) {
                            successCount++;
                            console.log(`删除ID ${task.id} 成功`);
                        } else {
                            failCount++;
                            failedIds.push(task.id);
                            console.error(`删除ID ${task.id} 失败:`, response.data.message);
                        }
                    } else {
                        failCount++;
                        failedIds.push(deleteTasks[index].id);
                        console.error(`删除ID ${deleteTasks[index].id} 出错:`, result.reason);
                    }
                });
                
                
                // 5. 处理删除结果
                if (failCount === 0) {
                    ElMessage.success(`批量删除成功，共删除 ${successCount} 条记录`);
                } else if (successCount > 0) {
                    ElMessage.warning(`部分删除成功，成功 ${successCount} 条，失败 ${failCount} 条`);
                    if (failedIds.length > 0) {
                        console.log('删除失败的ID列表:', failedIds);
                    }
                } else {
                    ElMessage.error('批量删除失败');
                }
                
                // 刷新数据
                GetBom();
                multipleSelection.value = []; // 清空选择状态，重置UI
                
            } catch (error) {
                // 6. 处理网络错误或其他异常
                ElMessage.error('批量删除失败，请重试');
                console.error('Batch delete error:', error);
            }
        })
        .catch(() => {
            // 7. 用户取消删除操作
            ElMessage.info('已取消批量删除');
        });
};
</script>

<style scoped>
.green-text {
    color: #67C23A;
}

.red-text {
    color: #F56C6C;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 10px;
    background-color: #f9fafb;
    border-radius: 8px;
}

.custom-pagination {
    --el-pagination-item-size: 32px;
    --el-pagination-item-bg: #ffffff;
    --el-pagination-item-color: #606266;
    --el-pagination-item-hover-color: #4096ff;
    --el-pagination-item-active-color: #ffffff;
    --el-pagination-item-active-bg: #4096ff;
    --el-pagination-border-radius: 6px;
    --el-pagination-margin: 0 5px;
}

.custom-pagination .el-pagination__prev,
.custom-pagination .el-pagination__next {
    width: 32px;
    height: 32px;
    border-radius: 6px;
}

.custom-pagination .el-pagination__sizes {
    margin-right: 10px;
}

.custom-pagination .el-pagination__total {
    margin-right: 10px;
    color: #606266;
}

.custom-pagination .el-pagination__item {
    margin: 0 5px;
    border-radius: 6px;
    min-width: 32px;
    height: 32px;
    line-height: 32px;
}

.custom-pagination .el-pagination__item:hover {
    background-color: #f0f5ff;
}

.custom-pagination .el-pagination__item.is-active {
    background-color: #4096ff;
    color: #ffffff;
}

/* 选择下级对话框样式 */
.selection-container {
    display: flex;
    flex-direction: column;
    height: 600px;
    background-color: #f5f7fa;
}

.selection-header {
    padding: 10px;
    font-weight: bold;
    border-bottom: 1px solid #dcdfe6;
}

.selection-panels {
    display: flex;
    flex: 1;
    padding: 10px;
}

.left-panel, .right-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
    overflow: hidden;
}

.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
}

.refresh-icon {
    cursor: pointer;
}

.search-box {
    padding: 10px;
}

.material-table {
    flex: 1;
    overflow: auto;
}

.transfer-buttons {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 0 20px;
}

.arrow-right, .arrow-left {
    width: 32px;
    height: 32px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #409eff;
    color: white;
    border-radius: 50%;
    margin: 10px 0;
    cursor: pointer;
}

.arrow-left {
    background-color: #909399;
}

.pagination-mini {
    padding: 10px;
    display: flex;
    justify-content: center;
}

.empty-data {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #909399;
}

.empty-icon {
    font-size: 48px;
    margin-bottom: 10px;
}

.empty-text {
    font-size: 14px;
}

/* 选中行样式 */
.selected-row {
    background-color: #e6f7ff !important;
}

.selected-row:hover {
    background-color: #bae7ff !important;
}

/* 展开行样式 */
.no-children {
    padding: 20px;
    background-color: #f9f9f9;
}

.el-table__expand-icon {
    transition: transform 0.2s ease-in-out;
    cursor: pointer;
}

.el-table__expand-icon--expanded {
    transform: rotate(90deg);
}

.el-table__expanded-cell {
    padding: 20px !important;
    background-color: #f9fafb !important;
}

.el-table__expanded-cell .el-table {
    margin-bottom: 0;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 子表格样式 */
.el-table__expanded-cell .el-table th {
    background-color: #eef1f6 !important;
    color: #606266;
    font-weight: 600;
}

.el-table__expanded-cell .el-empty {
    padding: 30px 0;
}
</style>
